import React, {Component} from 'react';
import {BackHandler, ToastAndroid, Platform} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import HomePage from './home';
import ErrorPage from './error';
import MyPage from './my';

const tabBarIcon = name => ({tintColor}) => (
  <FontAwesome
    style={{backgroundColor: 'transparent'}}
    name={name}
    color={tintColor}
    size={20}
  />
);

class Home extends Component {
  static navigationOptions = {
    tabBarIcon: tabBarIcon('home'),
    tabBarLabel: '首页',
  };
  componentDidMount() {
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackHandler);
    }
  }

  //移除
  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackHandler);
    }
  }

  onBackHandler = () => {
    if (currentScreen == 'home' || currentScreen == 'login') {
      if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
        BackHandler.exitApp();
        return false;
      }
      this.lastBackPressed = Date.now();
      ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
      return true; //默认
    } else {
      return false;
    }
  };

  render() {
    global.navigation = this.props.navigation;
    return <HomePage navigation={this.props.navigation} />;
  }
}

class Error extends Component {
  static navigationOptions = {
    tabBarIcon: tabBarIcon('bell'),
    tabBarLabel: '报警',
  };
  render() {
    return <ErrorPage navigation={this.props.navigation} />;
  }
}

class My extends Component {
  static navigationOptions = {
    tabBarIcon: tabBarIcon('user'),
    tabBarLabel: '我的',
  };
  render() {
    return <MyPage navigation={this.props.navigation} />;
  }
}

const MainBar = createMaterialBottomTabNavigator(
  {
    home: {screen: Home},
    error: {screen: Error},
    My: {screen: My},
  },
  {
    initialRouteName: 'home',
    // order: ['Settings', 'Home'],
    activeColor: '#4f9fcf',
    inactiveColor: '#333',
    //   navigationOptions: ({ navigation }) => {
    //     const routeName = navigation.state.routeName;
    //     console.log("navigation 对象", navigation);
    //     return {
    //       title: routeName
    //     };
    //   },
    // inactiveTintColor: '#333',
    // 缩放图标的效果
    // shifting: true, // 默认在大于3个路由时为true, 如果显式的设置为true了则少于3个时也会显示效果
    barStyle: {
      backgroundColor: 'white',
    },
  },
)
export default MainBar;
